package org.exhaust.framework.net.test.protocol.client.tcp.app;

import lombok.extern.slf4j.Slf4j;
import org.exhaust.framework.net.client.tcp.BaseTcpClient;
import org.exhaust.framework.net.client.tcp.TcpClient;
import org.exhaust.framework.net.client.tcp.TcpClientProperty;
import org.exhaust.framework.net.client.tcp.handler.TcpReconnectChannelEventHandler;
import org.exhaust.framework.net.common.protocol.ChannelEventDispatcher;
import org.exhaust.framework.net.common.protocol.encoder.TcpFrameToByteBufEncoder;
import org.exhaust.framework.net.test.protocol.client.tcp.decoder.ServerGprsMsgDecoderNoneSharable;
import org.exhaust.framework.net.test.protocol.client.tcp.handler.AuthEventHandler;

import java.util.concurrent.CountDownLatch;

@Slf4j
public class TcpClientApplication {
    public static void main(String[] args) throws Exception {

        ChannelEventDispatcher dispatcher = new ChannelEventDispatcher();

        TcpClientProperty property = new TcpClientProperty();
        property.setConnectTimeout(5000);
        property.setServerAddress("127.0.0.1");
        property.setServerPort(8018);
        property.setWriterIdleSeconds(30);
        property.setReaderIdleSeconds(30);

        TcpFrameToByteBufEncoder encoder = new TcpFrameToByteBufEncoder();

        boolean enableReconnect = true;

        boolean enableAuth = true;

        String id = "15871401686";

        TcpClient tcpClient = new BaseTcpClient(() -> {
            return new ServerGprsMsgDecoderNoneSharable();
        }, encoder, dispatcher, property);

        if (enableAuth) {
            dispatcher.addChannelHandler(new AuthEventHandler("15871401686"));
        }
        if (enableReconnect) {
            dispatcher.addChannelHandler(new TcpReconnectChannelEventHandler(tcpClient));
        }

        new Thread(() -> {
            try {
                tcpClient.start();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }).start();

        CountDownLatch latch = new CountDownLatch(1);
        latch.await();

    }
}
